package com.cqcvc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cqcvc.entity.Role;
import com.cqcvc.mapper.RoleMapper;
import com.cqcvc.mapper.RolePermissionMapper;
import com.cqcvc.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqcvc.util.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hunter
 * @since 2022-08-04
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public Set<String> getRolesByUsername(String username) {
        return roleMapper.selectRolesByUsername(username);
    }

    @Override
    public Map<String, Object> selectRole(String pageNum, String pageSize) {
        int first = StringUtil.isNullOrEmpty(pageNum) ? 1 : Integer.parseInt(pageNum);
        int second = StringUtil.isNullOrEmpty(pageSize) ? 5 : Integer.parseInt(pageSize);
        PageHelper.startPage(first,second);
        QueryWrapper qw=new QueryWrapper();
        List<Role> list=roleMapper.selectList(qw);
        PageInfo pageInfo=new PageInfo(list);
        Map<String, Object> map=new HashMap<>();
        map.put("total",pageInfo.getTotal());
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(Role role:list){
            Map<String,Object> map1=new HashMap<>();
            map1.put("role",role);
            mapList.add(map1);
        }
        map.put("list",mapList);
        return  map;
    }

    @Override
    public int saveRole(Role role) {
        int i;
        if(StringUtil.isNullOrEmpty(role.getRoleId())){
            i=roleMapper.insert(role);
        }else{
            i=roleMapper.updateById(role);
        }
        return i;
    }

    @Override
    public int delRole(int id) {
        //级联删除role_permission表对应信息
        QueryWrapper qw=new QueryWrapper<>();
        qw.eq("role_id",id);
        rolePermissionMapper.delete(qw);
        return roleMapper.deleteById(id);
    }

    @Override
    public Integer batchDel(List<Integer> ids) {
        //级联删除role_permission表对应信息
        for(Integer rid:ids){
            QueryWrapper qw=new QueryWrapper<>();
            qw.eq("role_id",rid);
            rolePermissionMapper.delete(qw);
        }
        return roleMapper.deleteBatchIds(ids);
    }

    @Override
    public Role selectByRoleId(Integer rid) {
        return roleMapper.selectById(rid);
    }
}
